<template>
  <div>
    <nav-com
      :title="title"
      :showView="true"
      @back="backHandler()"
    ></nav-com>
    <van-form @submit="onSubmit">
      <van-cell-group>
        <van-field
          v-model="addressInfo.name"
          name="name"
          label-width="4rem"
          label="姓名"
          placeholder="收货人姓名"
          :rules="[
            { required: true, message: '' },
            { validator: validatorName, message: '最大长度不能超过12个字符' },
          ]"
        ></van-field>
        <van-field
          v-model="addressInfo.tel"
          name="tel"
          label-width="4rem"
          label="手机号"
          placeholder="收货人手机号"
          :rules="[
            { required: true, message: '' },
            { validator: validatorphone, message: '格式不正确' },
          ]"
        ></van-field>
        <van-field
          v-model="addressInfo.address"
          is-link
          readonly
          name="address"
          label-width="4rem"
          label="收货地址"
          @click="showArea = true"
          placeholder="选择省/市/区"
          :rules="[{ required: true, message: '' }]"
        ></van-field>
        <van-field
          v-model="addressInfo.addressDetail"
          name="addressDetail"
          label-width="4rem"
          label="详细地址"
          placeholder="如道路、门牌号、小区、楼栋号、单元室等"
          :rules="[
            { required: true, message: '' },
            {
              validator: validatorAddress,
              message: '最大长度不能超过66个字符',
            },
          ]"
        ></van-field>
        <van-cell
          center
          title="设为默认地址"
        >
          <template #right-icon>
            <van-switch
              v-model="checked"
              size="24"
              active-color="#FE4B20"
            />
          </template>
        </van-cell>
      </van-cell-group>
      <div style="margin: 12px">
        <van-button
          round
          block
          color="#FE4B20"
          native-type="submit"
        >保存</van-button>
      </div>
    </van-form>
    <div style="margin: 12px; color: #000">
      <van-button
        v-if="!is_add"
        round
        block
        color="#E7E7E7"
        @click="delect"
      ><span style="color: #000">删除地址</span></van-button>
    </div>
    <van-popup
      v-model="showArea"
      round
      position="bottom"
    >
      <van-cascader
        v-model="cascaderValue"
        title="请选择所在地区"
        :options="options"
        @finish="onFinish"
        @close="showArea = false"
        @change="onChange"
        :field-names="fieldNames"
      />
    </van-popup>
  </div>
</template>

<script>
// import { option } from "@/api/areaData.js";
import { getArea } from "@/api/areaApi";
import { delReceipt, addReceipt, editReceipt } from "@/api/api";
import navCom from "@/component/nav";
import { Toast } from "vant";
const config = {
  headers:{
    'Authorization': localStorage.getItem("token"),
    'token': localStorage.getItem("token")
  }
};

export default {
  components: {
    navCom,
  },
  data() {
    return {
      checked: true,
      showArea: false,
      showView: true,
      options: [],
      fieldNames: {
        text: "name",
        value: "id",
        children: "children",
      },
      cascaderValue: "",
      addressInfo: {
        name: "",
        tel: "",
        province: "",
        city: "",
        county: "",
        addressDetail: "",
        areaCode: "",
        address: "",
      },
      uid: weixin.getUserId(),
      id: 0,
      good_id: "",
      has_order: "",
      order_sn: "",
      one_day: "",
      is_add: false,
      title: "",
    };
  },
  mounted() {
    this.is_add = this.$route.params.isAdd || false;
    this.title = this.is_add ? "新增收货地址" : "修改收货地址";
    this.init();
    this.getAreaList(1);
  },
  methods: {
    async onChange(data) {
      console.log(data);
      let res = await this.getAreaList2or3(data.tabIndex + 2, data.value);
      this.addTree(data.selectedOptions, res, data.value);
    },
    addTree(selectedOptions, children, id) {
      selectedOptions.forEach((item) => {
        if (item.id == id) {
          item.children = children;
        }
      });
    },
    // 获取二级3级地址
    async getAreaList2or3(level, pid) {
      let data;
      await getArea({ level, pid }).then((res) => {
        if (level !== 3) {
          res.data.data.forEach((item) => {
            item.children = [];
          });
        }
        data = res.data.data;
      });
      return data;
    },
    // 获取地区信息
    getAreaList(level, pid) {
      getArea({ level, pid })
        .then((result) => {
          result.data.data.forEach((item) => {
            item.children = [];
          });
          this.options = result.data.data;
          console.log(66, this.options);
          return result.data.data;
        })
        .catch((err) => {});
    },
    backHandler() {
      this.$router.go(-1);
    },
    init() {
      console.log(this.$route.params.detail);
      if (this.$route.params.detail != null) {
        let data = this.$route.params.detail;
        (this.addressInfo.name = data.consignee),
          (this.addressInfo.tel = data.phone),
          (this.addressInfo.addressDetail = data.address),
          (this.id = data.id);
        this.addressInfo.address =
          data.province_name + "-" + data.city_name + "-" + data.area_name;
      }
    },
    delect() {
      this.$dialog
        .alert({
          title: "删除地址",
          message: "亲，您确认要删除该地址吗？",
          confirmButtonText: "确定",
          showCancelButton: true,
          cancelButtonText: "取消",
        })
        .then(() => {

          let urls = `${localStorage.getItem("share_weixin_shareurl")}/addons/shopro/address/del`
          this.$axios.post(urls,{id: this.id},config).then(res=>{
            if (res.data.code == 1) {
              this.backHandler();
            } else {
              Toast(res.data.msg);
            }
          }).catch((err) => {});
        });
    },
    onSubmit(val) {
      let data = {
        id: this.id,
        consignee: val.name,
        phone: val.tel,
        area_text: val.address,
        address: val.addressDetail,
        is_default: this.checked,
        latitude: "",
        longitude: "",
      };
      let urls = `${localStorage.getItem("share_weixin_shareurl")}/addons/shopro/address/edit`
      this.$axios.post(urls,data,config).then(res=>{
        if (this.id != 0) {
          Toast("修改成功");
        } else {
          Toast("新增成功");
        }
        if (res.data.code == 1) {
          this.$router.back();
          //this.$router.push({name:'pay'})
        } else {
          this.$dialog.alert({
            message: res.data.msg,
          });
        }
      }).catch((err) => {});
    },
    //判断姓名
    validatorName(val) {
      if (val.length > 12) return false;
    },
    //判断电话
    validatorphone(val) {
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!reg.test(val)) {
        return false;
      } else {
        return true;
      }
    },
    //详细地址
    validatorAddress(val) {
      if (val.length > 66) return false;
    },
    //地区选择完成
    onFinish(val) {
      this.showArea = false;
      this.addressInfo.address = val.selectedOptions
        .map((item) => item.name)
        .join("-");
    },
  },
};
</script>

<style>
</style>
